import { memo, useState, useEffect, useCallback, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import type { CarouselSlide } from '@/types';

/**
 * 轮播图组件
 * @param slides 轮播图数据
 * @param autoPlay 是否自动轮播
 * @param interval 轮播间隔时间
 */

interface CarouselProps {
  slides: CarouselSlide[];
  autoPlay?: boolean;
  interval?: number;
}

export const Carousel = memo(({
  slides,
  autoPlay = true,
  interval = 5000
}: CarouselProps) => {
  // 当前图片索引
  const [currentIndex, setCurrentIndex] = useState(0);
  // 切换方向
  const [direction, setDirection] = useState(0);
  // 定时器
  const timerRef = useRef<NodeJS.Timeout | null>(null);
  // 切换到下一张图片
  const nextSlide = useCallback(() => {
    setDirection(1);
    // 切换到下一张图片,如果当前是最后一张,则切换到第一张
    if (currentIndex === slides.length - 1) {
      setCurrentIndex(0);
    } else {
      setCurrentIndex((prev) => (prev + 1) % slides.length);
    }
  }, [currentIndex, slides.length]);

  // 点击圆点 切换到指定索引的图片
  const goToSlide = useCallback((index: number) => {
    // 切换方向 如果当前索引大于目标索引,则切换方向为1,否则为-1
    setDirection(index > currentIndex ? 1 : -1);
    setCurrentIndex(index);
  }, [currentIndex]);
  // 启动定时器
  const startTimer = useCallback(() => {
    // 如果自动轮播为false,则不启动定时器
    if (!autoPlay) return;
    // 清除现有定时器
    if (timerRef.current) {
      clearInterval(timerRef.current);
    }
    // 设置新的定时器
    timerRef.current = setInterval(nextSlide, interval);
  }, [autoPlay, interval, nextSlide]);

  // 停止定时器
  const stopTimer = useCallback(() => {
    if (timerRef.current) {
      clearInterval(timerRef.current);
    }
  }, []);

  // 初始化定时器
  useEffect(() => {
    startTimer();
    return () => stopTimer();
  }, [startTimer, stopTimer]);

  // 鼠标悬停时暂停自动播放
  const handleMouseEnter = useCallback(() => {
    stopTimer();
  }, [stopTimer]);

  // 鼠标离开时恢复自动播放
  const handleMouseLeave = useCallback(() => {
    startTimer();
  }, [startTimer]);

  // 点击指示器时的处理
  const handleDotClick = useCallback((index: number) => {
    goToSlide(index);
    startTimer(); // 重新启动定时器
  }, [goToSlide, startTimer]);

  if (!slides.length) return null;

  return (
    <div
      className="relative w-full h-[400px] overflow-hidden rounded-xl"
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
    >
      <AnimatePresence initial={false} custom={direction} mode='popLayout'>
        <motion.div
          key={currentIndex}
          custom={direction}
          initial={{
            opacity: 0,
            x: direction > 0 ? 1000 : -1000
          }}
          animate={{
            opacity: 1,
            x: 0
          }}
          exit={{
            opacity: 0,
            x: direction > 0 ? -1000 : 1000
          }}
          transition={{
            type: "spring",
            stiffness: 300,
            damping: 30
          }}
          className="absolute w-full h-full"

        >
          <div className="relative w-full h-full">
            <img
              src={slides[currentIndex].imageUrl}
              alt={slides[currentIndex].title}
              className="w-full h-full object-cover"

            />
            <div className="absolute inset-0 bg-gradient-to-t from-black/60 to-transparent">
              <div className="cursor-pointer absolute bottom-0 left-0 right-0 p-8 text-white"
                onClick={() => {
                  window.open(slides[currentIndex].link)
                }}
              >
                <motion.h2
                  initial={{ opacity: 0, x: -100 }}
                  animate={{ opacity: 1, x: 0 }}
                  transition={{ duration: 0.5, delay: 0.1 }}
                  className="text-3xl font-bold mb-2">{slides[currentIndex].title}</motion.h2>
                <motion.p
                  initial={{ opacity: 0, x: -100 }}
                  animate={{ opacity: 1, x: 0 }}
                  transition={{ duration: 0.5, delay: 0.2 }}
                  className="text-lg opacity-90">{slides[currentIndex].description}</motion.p>
              </div>
            </div>
          </div>
        </motion.div>
      </AnimatePresence>

      {/* 指示器 */}
      <div className="absolute bottom-4 left-1/2 -translate-x-1/2 flex space-x-2">
        {slides.map((_, index) => (
          <button
            key={index}
            onClick={() => handleDotClick(index)}
            className={`w-2 h-2 rounded-full transition-all ${index === currentIndex
              ? 'bg-white w-8'
              : 'bg-white/50 hover:bg-white/70'
              }`}
          />
        ))}
      </div>
    </div>
  );
});

Carousel.displayName = 'Carousel'; 